/*
 * To change this template, choose Tools | Templates
 * and open the template in the editor.
 */
package sft.Principal;

import Help.Log.JDAjuda;
import Help.Log.JILog;
import Interface.Insumos.Atendente.jIAtendente;
import Interface.Insumos.Convenio.DePara.jIDePara;
import Interface.Insumos.Convenio.jIConvenio;
import Interface.Insumos.Unidade.jIUnidade;
import Interface.Insumos.nConformidade.jInConformidade;
import Interface.Producao.JIProducao;
import java.awt.event.ActionEvent;
import java.awt.event.ActionListener;
import java.sql.SQLException;
import java.text.SimpleDateFormat;
import java.util.Date;
import java.util.List;
import java.util.logging.Level;
import java.util.logging.Logger;
import javax.swing.JOptionPane;
import javax.swing.Timer;
import sft.Atualizacao.LerVersao;
import sft.Autenticacao.Login.GUI.JICad_Login;
import sft.Autenticacao.Observacao;
import sft.Autenticacao.Sessao;
import sft.Autenticacao.jDLogin;
import sft.Autenticacao.jDNovaSenha;
import sft.Autenticacao.perfil.GUI.JIPerfil;
import sft.Autenticacao.perfil.logica.PerfilAcesso;
import sft.BancodeDados.Query;
import sft.Logica.Insumos;

/**
 *
 * @author Adriano
 */
public class Principal extends javax.swing.JFrame {

    
    
    //Codigos de inicalização.
    private static Principal t = null;
    //singleton classe principal

    public static Principal getInstance() {
        if (t == null) {
            t = new Principal();
        }
        return t;
    }
    private static jDLogin login;

    public final void Autenticacao() {
        if (login == null) {
            login = new jDLogin(t, true);
            login.setLocationRelativeTo(this);
            login.setVisible(true);
            
        }
        if(Sessao.getInstance().getUsuario() == null){
            System.exit(0);
        }
    }
    //Relogio e Observador de Log

    private void hora() {
        Timer timer = new Timer(1, new ActionListener() {
            @Override
            public void actionPerformed(ActionEvent e) {
                atualizaHora();
            }
        });
        timer.start();
    }

    public void atualizaHora() {

        Date data = new Date();
        SimpleDateFormat formato = new SimpleDateFormat("dd/MM/yyyy  -  HH:mm:ss");

        Observacao.getInstance().setData(formato.format(data));
        jLDataHora.setText(formato.format(data));
        jLUsuario.setText(Sessao.getInstance().getUsuario().getNome());
        jLAcao.setText(Observacao.getInstance().getAcao());
        jLServer.setText(Sessao.getInstance().getServidor());
    }
    
    public Principal() {
        Autenticacao();
        initComponents();
        hora();
        setLocationRelativeTo(t);
        super.setTitle("SISTEMA FATURAMENTO TOMMASI - SFT");
//        setInsumos();
        permissao();
    }
    public Principal(int n){
    }

    /**
     * This method is called from within the constructor to initialize the form.
     * WARNING: Do NOT modify this code. The content of this method is always
     * regenerated by the Form Editor.
     */
    @SuppressWarnings("unchecked")
    // <editor-fold defaultstate="collapsed" desc="Generated Code">//GEN-BEGIN:initComponents
    private void initComponents() {

        PainelPrincipal = new javax.swing.JPanel();
        Display = new javax.swing.JPanel();
        jLUsuario = new javax.swing.JLabel();
        jLAcao = new javax.swing.JLabel();
        jLServer = new javax.swing.JLabel();
        jLDataHora = new javax.swing.JLabel();
        jMenuBar1 = new javax.swing.JMenuBar();
        jMenu1 = new javax.swing.JMenu();
        jMProducao = new javax.swing.JMenuItem();
        jMenu3 = new javax.swing.JMenu();
        jMUser = new javax.swing.JMenuItem();
        jMPerfil = new javax.swing.JMenuItem();
        jSeparator1 = new javax.swing.JPopupMenu.Separator();
        jMAten = new javax.swing.JMenuItem();
        jMConv = new javax.swing.JMenuItem();
        jMUnid = new javax.swing.JMenuItem();
        jMNCon = new javax.swing.JMenuItem();
        jMConvDePara = new javax.swing.JMenuItem();
        jMenu2 = new javax.swing.JMenu();
        jMLog = new javax.swing.JMenuItem();
        jMSenha = new javax.swing.JMenuItem();
        jMSobre = new javax.swing.JMenuItem();

        setDefaultCloseOperation(javax.swing.WindowConstants.EXIT_ON_CLOSE);

        Display.setBorder(javax.swing.BorderFactory.createEtchedBorder());

        jLUsuario.setAutoscrolls(true);

        jLAcao.setAutoscrolls(true);

        jLDataHora.setAutoscrolls(true);

        javax.swing.GroupLayout DisplayLayout = new javax.swing.GroupLayout(Display);
        Display.setLayout(DisplayLayout);
        DisplayLayout.setHorizontalGroup(
            DisplayLayout.createParallelGroup(javax.swing.GroupLayout.Alignment.LEADING)
            .addGroup(DisplayLayout.createSequentialGroup()
                .addContainerGap()
                .addComponent(jLUsuario)
                .addGap(89, 89, 89)
                .addComponent(jLAcao)
                .addGap(30, 30, 30)
                .addComponent(jLServer)
                .addPreferredGap(javax.swing.LayoutStyle.ComponentPlacement.RELATED, 744, Short.MAX_VALUE)
                .addComponent(jLDataHora)
                .addGap(153, 153, 153))
        );
        DisplayLayout.setVerticalGroup(
            DisplayLayout.createParallelGroup(javax.swing.GroupLayout.Alignment.LEADING)
            .addGroup(DisplayLayout.createSequentialGroup()
                .addGroup(DisplayLayout.createParallelGroup(javax.swing.GroupLayout.Alignment.LEADING)
                    .addComponent(jLServer)
                    .addComponent(jLDataHora)
                    .addComponent(jLAcao)
                    .addComponent(jLUsuario))
                .addContainerGap(javax.swing.GroupLayout.DEFAULT_SIZE, Short.MAX_VALUE))
        );

        javax.swing.GroupLayout PainelPrincipalLayout = new javax.swing.GroupLayout(PainelPrincipal);
        PainelPrincipal.setLayout(PainelPrincipalLayout);
        PainelPrincipalLayout.setHorizontalGroup(
            PainelPrincipalLayout.createParallelGroup(javax.swing.GroupLayout.Alignment.LEADING)
            .addComponent(Display, javax.swing.GroupLayout.DEFAULT_SIZE, javax.swing.GroupLayout.DEFAULT_SIZE, Short.MAX_VALUE)
        );
        PainelPrincipalLayout.setVerticalGroup(
            PainelPrincipalLayout.createParallelGroup(javax.swing.GroupLayout.Alignment.LEADING)
            .addGroup(javax.swing.GroupLayout.Alignment.TRAILING, PainelPrincipalLayout.createSequentialGroup()
                .addContainerGap(683, Short.MAX_VALUE)
                .addComponent(Display, javax.swing.GroupLayout.PREFERRED_SIZE, javax.swing.GroupLayout.DEFAULT_SIZE, javax.swing.GroupLayout.PREFERRED_SIZE))
        );

        jMenu1.setMnemonic('C');
        jMenu1.setText("Cadastro");
        jMenu1.setToolTipText("");
        jMenu1.addActionListener(new java.awt.event.ActionListener() {
            public void actionPerformed(java.awt.event.ActionEvent evt) {
                jMenu1ActionPerformed(evt);
            }
        });

        jMProducao.setAccelerator(javax.swing.KeyStroke.getKeyStroke(java.awt.event.KeyEvent.VK_P, java.awt.event.InputEvent.CTRL_MASK));
        jMProducao.setText("Produção");
        jMProducao.setToolTipText("");
        jMProducao.addActionListener(new java.awt.event.ActionListener() {
            public void actionPerformed(java.awt.event.ActionEvent evt) {
                jMProducaoActionPerformed(evt);
            }
        });
        jMenu1.add(jMProducao);

        jMenu3.setText("Administrador");

        jMUser.setAccelerator(javax.swing.KeyStroke.getKeyStroke(java.awt.event.KeyEvent.VK_U, java.awt.event.InputEvent.CTRL_MASK));
        jMUser.setText("Usuario");
        jMUser.addActionListener(new java.awt.event.ActionListener() {
            public void actionPerformed(java.awt.event.ActionEvent evt) {
                jMUserActionPerformed(evt);
            }
        });
        jMenu3.add(jMUser);

        jMPerfil.setAccelerator(javax.swing.KeyStroke.getKeyStroke(java.awt.event.KeyEvent.VK_A, java.awt.event.InputEvent.CTRL_MASK));
        jMPerfil.setText("Perfil");
        jMPerfil.addActionListener(new java.awt.event.ActionListener() {
            public void actionPerformed(java.awt.event.ActionEvent evt) {
                jMPerfilActionPerformed(evt);
            }
        });
        jMenu3.add(jMPerfil);

        jMenu1.add(jMenu3);
        jMenu1.add(jSeparator1);

        jMAten.setAccelerator(javax.swing.KeyStroke.getKeyStroke(java.awt.event.KeyEvent.VK_F1, 0));
        jMAten.setText("Atendente");
        jMAten.addActionListener(new java.awt.event.ActionListener() {
            public void actionPerformed(java.awt.event.ActionEvent evt) {
                jMAtenActionPerformed(evt);
            }
        });
        jMenu1.add(jMAten);

        jMConv.setAccelerator(javax.swing.KeyStroke.getKeyStroke(java.awt.event.KeyEvent.VK_F2, 0));
        jMConv.setText("Convenio");
        jMConv.addActionListener(new java.awt.event.ActionListener() {
            public void actionPerformed(java.awt.event.ActionEvent evt) {
                jMConvActionPerformed(evt);
            }
        });
        jMenu1.add(jMConv);

        jMUnid.setAccelerator(javax.swing.KeyStroke.getKeyStroke(java.awt.event.KeyEvent.VK_F3, 0));
        jMUnid.setText("Unidade");
        jMUnid.addActionListener(new java.awt.event.ActionListener() {
            public void actionPerformed(java.awt.event.ActionEvent evt) {
                jMUnidActionPerformed(evt);
            }
        });
        jMenu1.add(jMUnid);

        jMNCon.setAccelerator(javax.swing.KeyStroke.getKeyStroke(java.awt.event.KeyEvent.VK_F4, 0));
        jMNCon.setText("Não Conformidade");
        jMNCon.addActionListener(new java.awt.event.ActionListener() {
            public void actionPerformed(java.awt.event.ActionEvent evt) {
                jMNConActionPerformed(evt);
            }
        });
        jMenu1.add(jMNCon);

        jMConvDePara.setAccelerator(javax.swing.KeyStroke.getKeyStroke(java.awt.event.KeyEvent.VK_F5, 0));
        jMConvDePara.setText("DePara Convenio");
        jMConvDePara.addActionListener(new java.awt.event.ActionListener() {
            public void actionPerformed(java.awt.event.ActionEvent evt) {
                jMConvDeParaActionPerformed(evt);
            }
        });
        jMenu1.add(jMConvDePara);

        jMenuBar1.add(jMenu1);

        jMenu2.setText("Ajuda");

        jMLog.setAccelerator(javax.swing.KeyStroke.getKeyStroke(java.awt.event.KeyEvent.VK_H, java.awt.event.InputEvent.CTRL_MASK));
        jMLog.setText("Historico");
        jMLog.addActionListener(new java.awt.event.ActionListener() {
            public void actionPerformed(java.awt.event.ActionEvent evt) {
                jMLogActionPerformed(evt);
            }
        });
        jMenu2.add(jMLog);

        jMSenha.setText("Trocar Senha");
        jMSenha.addActionListener(new java.awt.event.ActionListener() {
            public void actionPerformed(java.awt.event.ActionEvent evt) {
                jMSenhaActionPerformed(evt);
            }
        });
        jMenu2.add(jMSenha);

        jMSobre.setText("Sobre");
        jMSobre.addActionListener(new java.awt.event.ActionListener() {
            public void actionPerformed(java.awt.event.ActionEvent evt) {
                jMSobreActionPerformed(evt);
            }
        });
        jMenu2.add(jMSobre);

        jMenuBar1.add(jMenu2);

        setJMenuBar(jMenuBar1);

        javax.swing.GroupLayout layout = new javax.swing.GroupLayout(getContentPane());
        getContentPane().setLayout(layout);
        layout.setHorizontalGroup(
            layout.createParallelGroup(javax.swing.GroupLayout.Alignment.LEADING)
            .addComponent(PainelPrincipal, javax.swing.GroupLayout.DEFAULT_SIZE, javax.swing.GroupLayout.DEFAULT_SIZE, Short.MAX_VALUE)
        );
        layout.setVerticalGroup(
            layout.createParallelGroup(javax.swing.GroupLayout.Alignment.LEADING)
            .addComponent(PainelPrincipal, javax.swing.GroupLayout.DEFAULT_SIZE, javax.swing.GroupLayout.DEFAULT_SIZE, Short.MAX_VALUE)
        );

        pack();
    }// </editor-fold>//GEN-END:initComponents

    private void jMenu1ActionPerformed(java.awt.event.ActionEvent evt) {//GEN-FIRST:event_jMenu1ActionPerformed
        // TODO add your handling code here:        
    }//GEN-LAST:event_jMenu1ActionPerformed

    private void jMProducaoActionPerformed(java.awt.event.ActionEvent evt) {//GEN-FIRST:event_jMProducaoActionPerformed
        // TODO add your handling code here:
        mostrarProducao();
    }//GEN-LAST:event_jMProducaoActionPerformed

    private void jMAtenActionPerformed(java.awt.event.ActionEvent evt) {//GEN-FIRST:event_jMAtenActionPerformed
        // TODO add your handling code here:
        mostrarAtendente();
    }//GEN-LAST:event_jMAtenActionPerformed

    private void jMConvActionPerformed(java.awt.event.ActionEvent evt) {//GEN-FIRST:event_jMConvActionPerformed
        // TODO add your handling code here:
        mostrarConvenio();
    }//GEN-LAST:event_jMConvActionPerformed

    private void jMUnidActionPerformed(java.awt.event.ActionEvent evt) {//GEN-FIRST:event_jMUnidActionPerformed

        mostrarUnidade();
    }//GEN-LAST:event_jMUnidActionPerformed

    private void jMNConActionPerformed(java.awt.event.ActionEvent evt) {//GEN-FIRST:event_jMNConActionPerformed
        // TODO add your handling code here:
        mostrarnConformidade();
    }//GEN-LAST:event_jMNConActionPerformed

    private void jMSobreActionPerformed(java.awt.event.ActionEvent evt) {//GEN-FIRST:event_jMSobreActionPerformed
        // TODO add your handling code here:
        new JDAjuda(this, true).setVisible(true);
    }//GEN-LAST:event_jMSobreActionPerformed

    private void jMLogActionPerformed(java.awt.event.ActionEvent evt) {//GEN-FIRST:event_jMLogActionPerformed
        // TODO add your handling code here:
        mostrarLog();
    }//GEN-LAST:event_jMLogActionPerformed

    private void jMSenhaActionPerformed(java.awt.event.ActionEvent evt) {//GEN-FIRST:event_jMSenhaActionPerformed
        // TODO add your handling code here:
       new jDNovaSenha(this, true).setVisible(true);
        
    }//GEN-LAST:event_jMSenhaActionPerformed

    private void jMUserActionPerformed(java.awt.event.ActionEvent evt) {//GEN-FIRST:event_jMUserActionPerformed
        // TODO add your handling code here:
        mostrarUsua();
    }//GEN-LAST:event_jMUserActionPerformed

    private void jMPerfilActionPerformed(java.awt.event.ActionEvent evt) {//GEN-FIRST:event_jMPerfilActionPerformed
        // TODO add your handling code here:
        mostrarPerfil();
    }//GEN-LAST:event_jMPerfilActionPerformed

    private void jMConvDeParaActionPerformed(java.awt.event.ActionEvent evt) {//GEN-FIRST:event_jMConvDeParaActionPerformed
        // TODO add your handling code here:
        mostrarDePara();
    }//GEN-LAST:event_jMConvDeParaActionPerformed

    /**
     * @param args the command line arguments
     */
    public static void main(String args[]) {
        /* Set the Nimbus look and feel */
        //<editor-fold defaultstate="collapsed" desc=" Look and feel setting code (optional) ">
        /* If Nimbus (introduced in Java SE 6) is not available, stay with the default look and feel.
         * For details see http://download.oracle.com/javase/tutorial/uiswing/lookandfeel/plaf.html 
         */
        try {
            for (javax.swing.UIManager.LookAndFeelInfo info : javax.swing.UIManager.getInstalledLookAndFeels()) {
                if ("Nimbus".equals(info.getName())) {
                    javax.swing.UIManager.setLookAndFeel(info.getClassName());
                    break;
                }
            }
        } catch (ClassNotFoundException ex) {
            java.util.logging.Logger.getLogger(Principal.class.getName()).log(java.util.logging.Level.SEVERE, null, ex);
        } catch (InstantiationException ex) {
            java.util.logging.Logger.getLogger(Principal.class.getName()).log(java.util.logging.Level.SEVERE, null, ex);
        } catch (IllegalAccessException ex) {
            java.util.logging.Logger.getLogger(Principal.class.getName()).log(java.util.logging.Level.SEVERE, null, ex);
        } catch (javax.swing.UnsupportedLookAndFeelException ex) {
            java.util.logging.Logger.getLogger(Principal.class.getName()).log(java.util.logging.Level.SEVERE, null, ex);
        }
        //</editor-fold>

        /* Create and display the form */
        java.awt.EventQueue.invokeLater(new Runnable() {
            public void run() {
                getInstance().setVisible(true);
            }
        });
    }
    // Variables declaration - do not modify//GEN-BEGIN:variables
    private javax.swing.JPanel Display;
    private javax.swing.JPanel PainelPrincipal;
    private javax.swing.JLabel jLAcao;
    private javax.swing.JLabel jLDataHora;
    private javax.swing.JLabel jLServer;
    private javax.swing.JLabel jLUsuario;
    private javax.swing.JMenuItem jMAten;
    private javax.swing.JMenuItem jMConv;
    private javax.swing.JMenuItem jMConvDePara;
    private javax.swing.JMenuItem jMLog;
    private javax.swing.JMenuItem jMNCon;
    private javax.swing.JMenuItem jMPerfil;
    private javax.swing.JMenuItem jMProducao;
    private javax.swing.JMenuItem jMSenha;
    private javax.swing.JMenuItem jMSobre;
    private javax.swing.JMenuItem jMUnid;
    private javax.swing.JMenuItem jMUser;
    private javax.swing.JMenu jMenu1;
    private javax.swing.JMenu jMenu2;
    private javax.swing.JMenu jMenu3;
    private javax.swing.JMenuBar jMenuBar1;
    private javax.swing.JPopupMenu.Separator jSeparator1;
    // End of variables declaration//GEN-END:variables
    private static JIProducao p1;
    
    private void permissao(){
        PerfilAcesso p = Sessao.getInstance().getUsuario().getPerfil();
        if(!p.isCad_aten()) jMAten.setVisible(false);
        if(!p.isCad_conv()) jMConv.setVisible(false);
        if(!p.isCad_conv_depara()) jMConvDePara.setVisible(false);
        if(!p.isCad_ncon()) jMNCon.setVisible(false);
        if(!p.isCad_unid()) jMUnid.setVisible(false); 
        if(!p.isCad_perfil()) jMPerfil.setVisible(false);
        if(!p.isCad_usua()) jMUser.setVisible(false);
    }
    
    
    public void ProdClose() {
        p1 = null;
    }

    private void mostrarProducao() {
        if (p1 == null) {
            p1 = new JIProducao(this);
            PainelPrincipal.add(p1);
            p1.setVisible(true);
        }
    }
   
    private static jIAtendente a1;

    public void AtenClose() {
       a1 = null;
    }

    private void mostrarAtendente() {
        // TODO add your handling code here:
        if (a1 == null) {
            a1 = new jIAtendente();
            PainelPrincipal.add(a1);
            a1.setVisible(true);
        }
    }
    //Convenio
    private static jIConvenio c1;
    public void ConvClose() {
        c1 = null;
    }
    
    private void mostrarConvenio() {
        // TODO add your handling code here:
        if (c1 == null) {
            c1 = new jIConvenio();
            PainelPrincipal.add(c1);
            c1.setVisible(true);
        }
    }
    
    private static jIUnidade u1;

    public void UnidClose() {
       u1 = null;
    }

    private void mostrarUnidade() {
        // TODO add your handling code here:
        if (u1 == null) {
            u1 = new jIUnidade();
            PainelPrincipal.add(u1);
            u1.setVisible(true);
        }
    }

    private static jInConformidade n1;

    public void nConClose() {
        n1 = null;
    }

    private void mostrarnConformidade() {
        // TODO add your handling code here:
        if (n1 == null) {
            n1 = new jInConformidade();
            PainelPrincipal.add(n1);
            n1.setVisible(true);
        }

    }
    
    private static JILog l1;
    public void LogClose(){
        l1 = null;
    }
    private void mostrarLog() {
        if(l1 == null){
            l1 = new JILog();
            PainelPrincipal.add(l1);
            l1.setVisible(true);
        }
    }
    
    private static JICad_Login l2;
    public void UserClose(){
        l2 = null;
    }
    private void mostrarUsua() {
        if(l2 == null){
            l2 = new JICad_Login(this);
            PainelPrincipal.add(l2);
            l2.setVisible(true);
        }
    }
    
    private static JIPerfil p2;
    public void PerfilClose(){
        p2 = null;
    }
    private void mostrarPerfil(){
        if(p2 == null){
            p2 = new JIPerfil(this);
            PainelPrincipal.add(p2);
            p2.setVisible(true);
        }
    }
    
    private static jIDePara dp;
    public void DeParaClose(){
        dp = null;
    }
    private void mostrarDePara() {
        if(dp == null){
            dp = new jIDePara(this);
            PainelPrincipal.add(dp);
            dp.setVisible(true);
        }
    }
    
    private static List<Insumos> aten;
    private static List<Insumos> conv;
    private static List<Insumos> ncon;
    private static List<Insumos> unid;
    private static List<Insumos> stat;
    private static List<Insumos> convenios;
    
    
    public static List<Insumos> getAten() {
        aten = boxQuery("sft_aten");
        return aten;
    }

    public static List<Insumos> getConv() {
        conv = boxQuery("sft_conv");
        return conv;
    }

    public static List<Insumos> getNcon() {
        ncon = boxQuery("sft_ncon");
        return ncon;
    }
    
    public static List<Insumos> getUnid(){
        unid = boxQuery("sft_unid");
        return unid;
    }
    
    public static List<Insumos> getStat() {
        stat = boxQuery("sft_stat");
        return stat;
    }
    
    public static List<Insumos> getConvenios() {
        try {
            convenios = new Query().getConvenios();
            return convenios;
        } catch (SQLException ex) {
            JOptionPane.showMessageDialog(null, "Erro ao carregar Insumos","ERRO",JOptionPane.ERROR_MESSAGE);
            Logger.getLogger(Principal.class.getName()).log(Level.SEVERE, null, ex);
        }
        return null;
    }
    
    public static int getVersao(){
        return new LerVersao().Config();
    }
    private static List<Insumos> boxQuery(String tabela) {
        try {
            List<Insumos> box;
            Insumos l = new Insumos();
            Query q = new Query();
            l.setSql("select * from " + tabela + " order by 2");                                      //primeira Linha vazia
            box = q.getList(0, l);
            for (int i = 0; i < box.size(); i++) {
                StringBuilder sb = new StringBuilder();
                sb.append(box.get(i).getNome().toUpperCase());
                if (sb.toString().contains("ZZ ")) {
//                    box.add(box.get(i));
                    box.remove(i);
                }
            }
            return box;
        } catch (SQLException ex) {
            JOptionPane.showMessageDialog(null, "Erro ao carregar Insumos","ERRO",JOptionPane.ERROR_MESSAGE);
            Logger.getLogger(Principal.class.getName()).log(Level.SEVERE, null, ex);
        }
        return null;
    }
    
//    public static void setInsumos() {
//        try {
//            aten = boxQuery("sft_aten");
//            conv = boxQuery("sft_conv");
//            ncon = boxQuery("sft_ncon");
//            unid = boxQuery("sft_unid");
//            convenios = new Query().getConvenios();
//            //stat = boxQuery("sft_stat");
//        } catch (SQLException ex) {
//            JOptionPane.showMessageDialog(null, "Erro ao carregar Insumos","ERRO",JOptionPane.ERROR_MESSAGE);
//            Logger.getLogger(Principal.class.getName()).log(Level.SEVERE, null, ex);
//        }
//    }
}
